package sevensoft.创建型模式.单例模式.破坏单例模式;

import org.junit.Test;
import sevensoft.创建型模式.单例模式.饿汉式.Singleton;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

public class 反射破坏方式 {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //破坏单例模式（已防止，自己去修改构造器逻辑）
        Class<Singleton> singletonClass = Singleton.class;
        Constructor<Singleton> declaredConstructor = singletonClass.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        Singleton singleton = declaredConstructor.newInstance();
        Singleton singleton1 = declaredConstructor.newInstance();
        System.out.println(singleton);
        System.out.println(singleton1);
        System.out.println(singleton1 == singleton);

//        Singleton instance = Singleton.getInstance();
//        Singleton instance1 = Singleton.getInstance();
//        System.out.println(instance1==instance);
    }

    @Test
    public void getRuntime() throws IOException {
        Runtime runtime = Runtime.getRuntime();
        Process ipconfig = runtime.exec("ipconfig");
        InputStream inputStream = ipconfig.getInputStream();
        int i;
        while ((i=inputStream.read())!=-1){
            System.out.print((char)i);
        }

    }

    @Test
    public void getMethod() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class<U1> u1Class = U1.class;
        Arrays.stream(u1Class.getMethods()).forEach(a -> {
            System.out.print(a.getName()+"(");
            Arrays.stream(a.getParameters()).forEach(p->{
                System.out.print(p+",");
            });
            System.out.print("):");
            System.out.println(a.getReturnType());
        });

        Method sss = u1Class.getDeclaredMethod("sss", String.class);
        sss.setAccessible(true);
        System.out.println(sss.invoke(null, "sss666"));

    }
}
